﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using E4RPTools;

namespace E4RPDevExpress9
{
    public class ListProfile
    {
        private static bool ExistsProfile(SqlTransaction sqlTransaction, string list, string name)
        {
            int count;
            const string query =
                @"  select	count(*)
		            from	E4RPListProfile
                    where   List = @List
                            and Name = @Name";
            using (var dataAccess = new SqlDataAccess())
                count = dataAccess.ExecuteScalar(sqlTransaction, 0, query, new SqlParameter("List", list),
                    new SqlParameter("Name", name));
            return count > 0;
        }

        private static void InsertProfile(SqlTransaction sqlTransaction, string list, string name, string xmlProfile)
        {
            const string query =
                @"  insert 
                    into    E4RPListProfile(List, Name, XmlProfile) 
                    values  (@List, @Name, @XmlProfile)";
            using (var sqlDataAccess = new SqlDataAccess())
                sqlDataAccess.ExecuteNonQuery(sqlTransaction, query, new SqlParameter("List", list),
                    new SqlParameter("Name", name), new SqlParameter("XmlProfile", xmlProfile));
        }

        private static void UpdateProfile(SqlTransaction sqlTransaction, string list, string name, string xmlProfile)
        {
            const string query =
                @"  update  E4RPListProfile 
                    set     XmlProfile = @XmlProfile
                    where   List = @List
                            and Name = @Name";
            using (var sqlDataAccess = new SqlDataAccess())
                sqlDataAccess.ExecuteNonQuery(sqlTransaction, query, new SqlParameter("List", list),
                    new SqlParameter("Name", name), new SqlParameter("XmlProfile", xmlProfile));
        }

        private static ListProfileDataSet GetListProfiles(SqlTransaction sqlTransaction, string list)
        {
            var dataSet = new ListProfileDataSet();
            const string query =
                @"  select	List, Name, XmlProfile
		            from	E4RPListProfile
                    where   List = @List
                    order by Name";
            using (var dataAccess = new SqlDataAccess())
                dataAccess.Fill(sqlTransaction, dataSet.ListProfile, query, new SqlParameter("List", list));
            return dataSet;
        }

        private static void SaveProfile(SqlTransaction sqlTransaction, string list, string name, string xmlProfile)
        {
            if (ExistsProfile(sqlTransaction, list, name))
                UpdateProfile(sqlTransaction, list, name, xmlProfile);
            else
                InsertProfile(sqlTransaction, list, name, xmlProfile);
        }


        private static ListProfileDataSet GetListLayouts(SqlConnection sqlConnection, IWin32Window ownerWindow, string logFile, string product, string list)
        {
            var sqlTransaction = sqlConnection.BeginTransaction();
            try
            {
                var dataSet = GetListProfiles(sqlTransaction, list);
                sqlTransaction.Commit();
                return dataSet;
            }
            catch (Exception e)
            {
                sqlTransaction.Rollback();
                ExceptionPublisher.PublishAndShowErrorMessage(ownerWindow, e, logFile, product, "Não foi possível ler a lista de perfis da lista.");
                return new ListProfileDataSet();
            }
        }

        private static List<string> GetProfiles(ListProfileDataSet dataSet)
        {
            var layouts = new List<string>();
            foreach (ListProfileDataSet.ListProfileRow layout in dataSet.ListProfile)
                layouts.Add(layout.Name);
            return layouts;
        }

        private static void SaveProfile(SqlConnection sqlConnection, string list, string name, string xmlProfile, IWin32Window ownerWindow, string logFile, string product)
        {
            var sqlTransaction = sqlConnection.BeginTransaction();
            try
            {
                SaveProfile(sqlTransaction, list, name, xmlProfile);
                sqlTransaction.Commit();
            }
            catch (Exception e)
            {
                sqlTransaction.Rollback();
                ExceptionPublisher.PublishAndShowErrorMessage(ownerWindow, e, logFile, product, "Não foi possível gravar perfil da lista.");
            }
        }




        public static string LoadProfile(SqlConnection sqlConnection, IWin32Window ownerWindow, string logFile, string product, GridView gridView, string list)
        {
            try
            {
                var dataSet = GetListLayouts(sqlConnection, ownerWindow, logFile, product, list);
                var form = new LoadLayoutXtraForm { Layouts = GetProfiles(dataSet) };
                if (form.ShowDialog() != DialogResult.OK)
                    return "";
                var xmlLayout = dataSet.ListProfile.FindByListName(list, form.LayoutName).XmlProfile;
                DevExpressHelper.RestoreLayoutFromXml(gridView, xmlLayout);
                return form.LayoutName;
            }
            catch (Exception)
            {
                return "";
            }
        }

        public static string SaveProfile(SqlConnection sqlConnection, IWin32Window ownerWindow, string logFile, string product, string list, string xmlProfile)
        {
            try
            {
                var dataSet = GetListLayouts(sqlConnection, ownerWindow, logFile, product, list);
                var form = new SaveLayoutXtraForm { OwnerWindow = ownerWindow, Layouts = GetProfiles(dataSet) };
                if (form.ShowDialog() != DialogResult.OK)
                    return "";
                SaveProfile(sqlConnection, list, form.LayoutName, xmlProfile, ownerWindow, logFile, product);
                return form.LayoutName;
            }
            catch (Exception)
            {
                return "";
            }
        }
    }
}
